define([
    'setting/validator',
    'formax/dialog',
    'bootstrap-datepicker',
    'jquery-form'
], function(vSetting) {

    // 获取 checkbox 选中数据
    $.fn.checkedValues = function() {
        var values = [];
        $(this).filter(':checked').each(function() {
            values.push(this.value);
        });
        return values;
    };

    // DOM 初始化
    $.fn.domInit = function() {

        var $dom = $(this);

        // AJAX 默认成功回调
        var ajaxSuccssCallback = function(data, redirect) {
            if (data.code !== 200) {
                return dialog.error(data.message);
            }

            var callback = function() {
                if (typeof redirect === 'string') {
                    document.location.href = redirect;
                } else {
                    document.location.reload();
                }
            };

            if (data.message) {
                return dialog.success(data.message, callback);
            }

            return callback(data);
        };

        // AJAX 表单默认处理
        var ajaxFormCallback = function(e) {
            e.preventDefault();
            var $form = $(this);
            $form.ajaxSubmit({
                beforeSubmit: function(arr) {
                    $form.trigger('ajax.form.before', arr);
                },
                error: function(xhr, error, status) {
                    $form.trigger('ajax.form.error', {
                        xhr: xhr,
                        error: error,
                        status: status
                    });
                },
                success: function(data) {
                    $form.trigger('ajax.form.success', data);
                }
            });
        };

        // 日期控件
        var $datepicker = $dom.find('.date-picker');
        if ($datepicker.length) {
            $.fn.datepicker.defaults['language'] = FORMAX.lang;
            $datepicker.datepicker();
        }

        // 全选/反选
        $dom.find('.group-checkable').each(function() {
            var $target = $($(this).data('target'));

            $(this).click(function() {
                var checked = $(this).is(':checked');

                $target.each(function() {
                    if (checked) {
                        $(this).prop('checked', true)
                            .closest('span').addClass('checked') // uniform
                        .closest('tr').addClass('active');
                    } else {
                        $(this).prop('checked', false)
                            .closest('span').removeClass('checked')
                            .closest('tr').removeClass('active');
                    }
                });
            });

            $target.each(function() {
                $(this).click(function() {
                    $(this).closest('tr').toggleClass('active');
                });
            });
        });


        // 表单处理
        $dom.find('form').each(function() {
            var $form = $(this);

            // 绑定所有控件，回车自动提交表单
            $form.find('input').keypress(function(e) {
                if (e.which == 13) {
                    $form.trigger('submit');
                    return false;
                }
            });

            // 表单自动验证
            for (key in vSetting) {
                var setting = vSetting[key];
                // ajax 表单处理
                if ($form.is('.form-ajax')) {
                    setting['submit'] = ajaxFormCallback;
                }
                $form.filter('.validator-' + key).addClass('form-validator').validator(setting);
            }

            // 自动提交搜索表单
            $form.filter('.form-search')
                .find('select,:checkbox,:radio,.date-picker')
                .change(function() {
                    $(this).closest('form').submit();
                });
        });

        // AJAX 表单
        $dom.find('form.form-ajax')
            .on('ajax.form.success', function(e, data) {
                ajaxSuccssCallback.call(this, data, $(this).data('redirect'));
            })
            .not('.form-validator').submit(ajaxFormCallback);

        // AJAX LINK
        $dom.find('a.ajax-link, a.ajax-delete').click(function(e) {
            e.preventDefault();

            var $self = $(this),
                redirect = $self.data('redirect');

            $self.on('ajax.get', function() {
                $.ajax({
                    url: $self.attr('href'),
                    dataType: 'json',
                    success: function(data) {
                        ajaxSuccssCallback.call(this, data, redirect);
                    }
                });
            });

            if ($self.is('.ajax-delete')) { // 删除链接，需要确认
                var message = $self.data('confirm') ? $self.data('confirm') : __('Are you sure you want to delete this record?');
                dialog.confirm(
                    '<span style="font-size:14px">' + message + '</span>',
                    function(result) {
                        if (result) {
                            $self.trigger('ajax.get');
                        }
                    }
                );
            } else {
                $self.trigger('ajax.get');
            }
        });

        // Modal 不使用 cache
        $dom.find('.modal').each(function() {
            var $self = $(this),
                dCache = $self.data('cache');

            // 自动初始化
            $self.on('shown.bs.modal', function() {
                App.initAjaxDialog();
                $self.domInit();
            });

            // 禁用缓存
            $self.on('hidden.bs.modal', function() {
                if (dCache === 'false' || dCache === 'off') {
                    $self.removeData('bs.modal');
                }
            });
        });

        return $dom;
    };

});
